package com.mybatisplus.socket_test1;

import java.io.*;
import java.net.Socket;

/**
 * @Auther: GongXl
 * @Date: 2021/3/2 10:05
 * @Description:
 */
public class TCPClient03 {
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket("127.0.0.1", 8989);
                    //客户端输入流
                    BufferedReader sin = new BufferedReader(new InputStreamReader(
                            System.in));
                    //向服务器发送消息输出流对象
                    DataOutputStream os = new DataOutputStream(socket.getOutputStream());
                    while (true) {
                        try {
                            //clinet监听键盘输入
                            String readline = sin.readLine();
                            System.out.println(readline);
                            //输出到服务端
                            os.writeUTF(readline);
                            os.flush();
                            if (readline.equals("exit")) {
                                break;
                            }
                            //启动一个专门的对服务器线程
                            Thread serveReceivTh = new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //开始监听服务器（广播）信息
                                    InputStream inputStream = null;
                                    try {
                                        inputStream = socket.getInputStream();
                                        byte[] buf = new byte[1024];
                                        int len;
                                        while((len = inputStream.read(buf)) != -1){
                                            String serveLine = new String(buf,0,len);
                                            System.out.println("服务器广播数据："+serveLine);
                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            serveReceivTh.start();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(runnable).start();

        while(true){}
    }
}